<?php
class Blogger_Posts extends Blogger_Db_Table_Abstract
{
	protected $_name = 'posts';
	protected $_primary = 'id';
	const PAGINATION_COUNT = 10;
	
	public function createPost($userId, $text, $title)
	{
		$userId = (int)$userId;
		$text = addslashes($text);
		$title = addslashes($title);
		$this->insert(array('users_id' => $userId,
							'contentText' => $text,
							'title' => $title,
							));
		return $this->getAdapter()->lastInsertId();
	}
	
	public function updatePost($postId, $userId, $text, $title)
	{
		$postId = (int)$postId;
		$userId = (int)$userId;
		$text = addslashes($text);
		$title = addslashes($title);
		$count = $this->update(array('contentText' => $text,
										'title' => $title,
										'lastModified' => new Zend_Db_Expr('NOW()'),
										), "id = $postId AND users_id = $userId");
		if(1 != $count)
			throw new Blogger_Exception("None or more than 1 record updated for postId = $postId & userId = $userId", Blogger_Exception_Codes::ERROR_CRITICAL);
	}
	
	public function getPaginatedPostsByUserId($userId)
	{
		$userId = (int)$userId;
		$adapter = new Zend_Paginator_Adapter_DbSelect(Zend_Registry::get('db')->select()
																				->from('posts')
																				->where("users_id = $userId"));
		return new Zend_Paginator($adapter);
	}
	
	public function getPostById($id)
	{
		$id = (int)$id;
		$row = $this->fetchRow("id = $id");
		if(empty($row))
			return null;
		else
			return array('id' => $id,
							'text' => stripslashes($row->contentText),
							'userId' => $row->users_id,
							'title' => stripslashes($row->title),
							'lastModified' => Blogger_Utilities::dateFormatter(strtotime($row->lastModified)),
						);
	}
	
	public function hasPost($userId, $postId)
	{
		$userId = (int)$userId;
		$postId = (int)$postId;
		$row = $this->fetchRow("id = $postId AND users_id = $userId");
		if(empty($row))
			return false;
		return array('id' => $postId,
						'usersId' => $userId,
						'text' => stripslashes($row->contentText),
						'title' =>  stripslashes($row->title),
						'lastModified' => Blogger_Utilities::dateFormatter(strtotime($row->lastModified)),
					);
	}
	
	public function deletePost($id)
	{
		$id = (int)$id;
		if(1 != $this->delete("id = $id"))
			throw new Blogger_Exception("None or more than 1 post deleted for id = $id", Blogger_Exception_Codes::ERROR_CRITICAL);
	}
	
	
}